/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.tutorial.actions;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import opiam.admin.faare.MessageUtil;
import opiam.admin.faare.exception.AuthenticationFailureException;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.services.StandardService;
import opiam.admin.faare.struts.utils.SessionContext;

/**
 * This class allows to log on.
 *
 * This Action class can not inherit from SecureAction class because the user
 * is not connected yet, or the SecureAction class checks that the user is
 * connected before calling the action methods.
 */
public class LogonAction extends Action
{
    /** Instance of the log4j logger.
     * Used to generate the execution traces. */
    private static Logger _logger =
        Logger.getLogger(LogonAction.class.getName());

    /**
     * This method is called to execute the action.
     *
     * @param mapping              Struts mapping data.
     * @param actionForm           FormBean associated with the action.
     * @param request              HTTP request.
     * @param httpServletResponse  HTTP response.
     *
     * @return An ActionForward.
     *
     * @throws IOException  An I/O exception if failed or interrupted I/O operations occurs.
     * @throws ServletException  A ServletException if the servlet has a problem.
     */
    @Override
	public ActionForward execute(ActionMapping mapping,
            ActionForm actionForm,
            HttpServletRequest request,
            HttpServletResponse httpServletResponse)
            throws IOException, ServletException
    {

        // Gets the login and password from the request.
        String login = request.getParameter("login");
        String password = request.getParameter("password");

        // Writes the login on the output defined in the
        // logger_config.properties.
        _logger.info("Logon with login : " + login);

        SessionContext sessionContext = null;
        UserContext userContext = null;
        ActionMessages msgErrors = new ActionMessages();

        try
        {
            // Generates an error if the login is empty.
            if ((login == null) || (login.trim().compareToIgnoreCase("") == 0))
            {
                // Gets the error message from the message-resources file
                // defined in the struts-config.xml
                msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("errors.required", "Login"));
                // Save the error message in the request to display it in the jsp
                // page.
                saveErrors(request, msgErrors);
            }

            // Generates an error if the password is empty.
            if ((password == null) ||
                    (password.trim().compareToIgnoreCase("") == 0))
            {
                // Gets the error message from the message-resources file
                // defined in the struts-config.xml
                msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("errors.required", "Password"));
                // Save the error message in the request to display it in the jsp
                // page.
                saveErrors(request, msgErrors);
            }

            // Generates an error if the login contains '*'.
            if ((login != null) && (login.indexOf("*") != -1))
            {
                // Gets the error message from the message-resources file
                // defined in the struts-config.xml
                msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("errors.login.star"));
                // Save the error message in the request to display it in the jsp
                // page.
                saveErrors(request, msgErrors);
            }

            // If errors are generated, returns the logon page.
            if (msgErrors.size() != 0)
            {
                // Returns the URI corresponding to the input of
                // the action as defined in the action configuration in the
                // struts-config.xml.
                return (mapping.getInputForward());
            }

            // Gets the session.
            HttpSession session = request.getSession();
            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);
            // Gets the user context.
            userContext = sessionContext.getUserContext();

            // Calls the StandardService to log on.
            StandardService.logon(login, password, userContext);

            // Sets the user object in the session.
            session.setAttribute("user", userContext.getJbUser());

            // Returns the URI corresponding to the action success
            // as defined in the action configuration in the struts-config.xml.
            return (mapping.findForward("success"));

        }
        catch (AuthenticationFailureException se)
        {
            // Writes the error on the output defined in the
            // logger_config.properties.
            _logger.info(MessageUtil.formatMessage("MSG_ERROR_LOGON", login));

            // Gets the error message from the message-resources file
            // defined in the struts-config.xml
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.auth.failed"));
            // Save the error message in the request to display it in the jsp
            // page.
            saveErrors(request, msgErrors);

            // Returns the URI corresponding to the input of
            // the action as defined in the action configuration in the
            // struts-config.xml.
            return (mapping.getInputForward());
        }
        catch (Exception se)
        {
            // Writes the error on the standard ouput console.
            se.printStackTrace();

            // Writes the error on the output defined in the
            // logger_config.properties.
            _logger.error(se.getMessage());

            // Gets the error message from the message-resources file
            // defined in the struts-config.xml
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.service.unknown"));
            // Save the error message in the request to display it in the jsp
            // page.
            saveErrors(request, msgErrors);

            // Returns the URI corresponding to the input of
            // the action as defined in the action configuration in the
            // struts-config.xml.
            return (mapping.getInputForward());
        }
    }
}
